import Vue from 'vue';
import moment from 'moment';
import lkeComponent from 'lke-component';
import App from './App.vue';
import Toast from '@/components/Toast';
import router from './router';
import { isMobile, getShareCode, getUserCategory } from '@/utils/util';
import mixin from '@/mixins/index.js';
import { ERROR_CODE } from './constants/error-code';
import { ChatUserCategory } from './constants';
import './utils/flexible-custom.js';
import { describeApp, getDemoToken } from './api/modules/auth.js';
Vue.use(lkeComponent);
const vhtml = window.vhtml;
Vue.use(vhtml);
vhtml.install(Vue);
try {
  let iconpath = 'https://cdn2.codesign.qq.com/icons/XzKaDZdEa7j2GPL/1747210455/iconfont.js';
  vhtml.Icon.setDefaultRemoteSrc && vhtml.Icon.setDefaultRemoteSrc(iconpath);
} catch (e) {
  console.log('加载icon错误');
}
// 把大写的键值对转为小写的
function convertKeys(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(item => convertKeys(item));
  }
  const newObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 转换键名
      const newKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
      // 处理连续下划线或开头下划线的情况
      const finalKey = newKey.replace(/^_+|_+$/g, '').replace(/_+/g, '_');
      // 递归处理值
      newObj[finalKey] = convertKeys(obj[key]);
    }
  }
  return newObj;
}
Vue.config.productionTip = false;
Vue.prototype.$toast = Toast;
Vue.prototype.moment = moment;
Vue.prototype.isMobile = isMobile();
Vue.prototype.isPhoneUser = getUserCategory() === ChatUserCategory.PHONE_NUMBER;
console.log('isMobile ==>', isMobile());
Vue.mixin(mixin);
router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? `${to.meta.title} | 知识库小助手` : '知识库小助手';
  next();
});

function getParameterByName(name) {
  name = name.replace(/[$$$$]/g, '\\$&');
  const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
  const results = regex.exec(window.location.href);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
const appBizId = getParameterByName('AppBizId');

// 区分会话端（1-坐席端 2-用户端）
let webIMType; // 后端ws识别的端类型
let webIMSource; // 前端区分UI交互的端类型

webIMType = [2];
window.$initTypeKey = 2;
webIMSource = 'client';

Vue.prototype.webIMSource = webIMSource;

Object.defineProperty(window, 'userType', {
  writable: false,
  enumerable: false,
  configurable: false,
  value: window.location.href.indexOf('workbench') > -1 ? 1 : 2
});

/**
   * 登录页无需水印
   * 因此只加在对话相关页面中
   */
window.CDSC_RTX = 'AI生成内容仅供参考';
window.WM_CDSC_EXT = Object;
window.WM_CDSC_EXT.cdsc_custom = '';
window.WM_CDSC_EXT.cdsc_alpha = 0.04;
window.WM_CDSC_EXT.cdsc_fontsize = '14px';
window.WM_CDSC_EXT.cdsc_zoom = 1;
window.WM_CDSC_EXT.cdsc_color = '#243861';
window.WM_CDSC_EXT.parent_node = 'app';

// sse不走获取token等接口
let tokenGet = webIMType.map(type => {
  return new Promise((resolve, reject) => {
    let result = {
      type: type
    };
    describeApp(appBizId).then(res => {
      const data = res.data;
      if (res.status == 200) {
        const obj = {};
        obj.AppType = data.AppType;
        obj.Avatar = data.BaseConfig.Avatar;
        obj.Balance = 1;
        obj.BotBizId = data.AppBizId;
        obj.ExperienceRecommendQuestion = [];
        obj.Greeting = data.AppConfig.KnowledgeQa.Greeting;
        obj.AiCall = data.AppConfig.KnowledgeQa.AiCall
        obj.InputLenLimit = 12000;
        obj.Name = data.BaseConfig.Name;
        obj.Pattern = "standard";
        obj.RecommendQuestions = [];
        obj.RequestId = data.RequestId;
        obj.SeatBizId = ""; // 字符串
        obj.SingleWorkflow = {
          "IsEnable": false,
          "Status": "",
          "WorkflowDesc": "",
          "WorkflowId": "",
          "WorkflowName": ""
        }
        obj.AppKey = data.AppKey;
        const newRes = convertKeys(obj);
        result = { ...result, ...newRes };
        const sharecode = getShareCode();
        window.localStorage.setItem('bot_biz_id_im', newRes.bot_biz_id || '');
        window.localStorage.setItem(`bot_biz_id_im_${sharecode}`, newRes.bot_biz_id || '');
        window.localStorage.setItem('seat_biz_id_im', newRes.seat_biz_id || '');
        window.localStorage.setItem('app_type', newRes.app_type || '');
        window.localStorage.setItem('balance', newRes.balance || null);
        let ret = {
          "AutoPlay": "",
          "SearchNetwork": "enable",
          "Stream": "enable",
          "WorkflowStatus": "enable"
        }
        if (data.AppConfig.KnowledgeQa && data.AppConfig.KnowledgeQa.Search) {
          // disable
          const rrr = data.AppConfig.KnowledgeQa.Search;
          for (let i = 0; i < rrr.length; i++) {
            if (rrr[i].Type == 'search') {
              rrr.SearchNetwork = rrr[i].Type.IsEnabled ? 'enable' : 'disable';
            }
          }
        }
        if (data.AppConfig.KnowledgeQa && data.AppConfig.KnowledgeQa.Search) {
          // disable
          const rrr = data.AppConfig.KnowledgeQa.Search;
          for (let i = 0; i < rrr.length; i++) {
            if (rrr[i].Type == 'search') {
              rrr.SearchNetwork = rrr[i].Type.IsEnabled ? 'enable' : 'disable';
            }
          }
        }

        const newRet = convertKeys(ret);
        result = { ...result, ...newRet };
        // console.log(obj,result,'resultresultresult')
        getDemoToken(obj.AppKey).then(response => {
          if (response.status  == 200) {
            let responseRes = {
              token: response.data.Token,
              access: 'ws'
            };
            result = { ...result, ...responseRes };
            resolve(result);
          }
        })

      }
    })
  })
})

Promise.all(tokenGet).then(res => {
  Object.defineProperty(window, 'webimToken', {
    writable: false,
    enumerable: false,
    configurable: false,
    value: res
  });
  console.log('【webim】  tokenGet---params-----》', webIMSource, res, window.webimToken);

  Vue.prototype.INVALID_SHARECODE = false;

  if (webIMSource === 'client') {
    (async () => {
      let mixin = await import('@/manage/index');
      Vue.mixin(mixin);
      /* eslint-disable no-new */
      new Vue({
        el: '#app',
        router,
        render(h) {
          return h(App);
        }
      }).$mount('#app');
    })();
  } else {
    
  }
}).catch(e => {
  if (e === ERROR_CODE.INVALID_SHARECODE) {
    Vue.prototype.INVALID_SHARECODE = true;
    (async () => {
      new Vue({
        el: '#app',
        router,
        render(h) {
          return h(App);
        }
      }).$mount('#app');
    })();
  }
});